package com.wzh.yebServe.config.security;

import com.wzh.yebServe.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author wzh
 * @create 2022/11/8 20:39
 * @Description: 进行授权校验
 */
public class JwtTokenFilter extends OncePerRequestFilter {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private MyUserDetailService myUserDetailService;


    /**
     * 前置拦截
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader(tokenHeader);
        //        说明token存在
        if (header!=null&&header.startsWith(tokenHead)){
//            从token中获取用户的信息,注意此处token的负载中只存储了username;
            String token = header.substring(tokenHead.length());
            String username = jwtTokenUtils.getUsernameFromToken(token);
//              登录未授权，token存在但是springsecurity全局中没有一个已经登录的对象，说明token存在，用户未登录
                if (username!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
//                    登录
                UserDetails userDetails = myUserDetailService.loadUserByUsername(username);

//              验证token是否有效，重新设置用户对象
                if (jwtTokenUtils.validateToken(token,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken=new
                            UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
